﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HousingInfo.Library;
using System.IO;

namespace NEWS.Admin
{
    public partial class Edit_AddNews : System.Web.UI.Page
    {
        private static string mode = null;
        private static NewsBO newsbo;
        private static bool retun = true;
        private static string _fileImageName;
        protected void Page_Load(object sender, EventArgs e)
        {
            //Mode Add
            if (!IsPostBack)
            {
                dltendanhmuc.DataSource = CategoryInfo.GetCategoryInfo_BySingle(false, false, false, true, true);
                dltendanhmuc.DataBind();

                mode = Request.QueryString["Mode"];
                if (mode != null)
                {
                    pn1.Visible = false;
                    newsbo = NewsBO.GetNewsBO(Convert.ToInt32(mode));
                    dltendanhmuc.SelectedValue = newsbo.CategoryID.ToString();
                    txtnewsid.Text = newsbo.NewsID.ToString();
                    dltendanhmuc.SelectedValue = newsbo.CategoryID.ToString();
                    string ten = dltendanhmuc.SelectedValue;
                    txttitle.Text = newsbo.Title;
                    txtnewscontent.Text = newsbo.NewsContent;
                    lbldatecreated.Text = newsbo.CreatedDate.ToString();
                    if (newsbo.IsActive == true)
                        isactive.Checked = true;
                    else isactive.Checked = false;
                    if (newsbo.UrlImage != "")
                    {
                        FileUpload_Image.Visible = false;
                        lbthuy.Visible = false;
                        txtimage.Visible = true;
                        txtimage.Text = newsbo.UrlImage;
                        txtimage.ReadOnly = true;
                        lbtthaydoi.Visible = true;
                    }
                }
                else
                {
                    lblheader.Text = "Đăng tin";
                    pn1.Visible = false;
                    pn2.Visible = false;
                    btnupdate.Text = "Thêm";
                }
            }
        }


        protected void btnback_Click(object sender, EventArgs e)
        {
            Response.Redirect("News.aspx");
        }
        protected void btnupdate_Click(object sender, EventArgs e)
        {
            if (mode != null)
            {   //Chinh sua tin
                int newsid = Convert.ToInt32(txtnewsid.Text);
                newsbo = NewsBO.GetNewsBO(newsid);
                newsbo.Title = txttitle.Text;
                newsbo.CategoryID = Convert.ToInt32(dltendanhmuc.SelectedValue);
                newsbo.NewsContent = txtnewscontent.Text;
                newsbo.IsActive = isactive.Checked;
                retun = true;
                if (FileUpload_Image.Visible == true)
                {
                    deleteExitsImage(newsbo.UrlImage);
                    if (FileUpload_Image.FileName.Length > 0)
                    {
                        postImage(FileUpload_Image);
                        if (retun == false) return;
                    }
                    else newsbo.UrlImage = "";
                }
                try
                {
                    newsbo.Save();
                    message.Text = "Cập nhật thành công !";
                    Response.Redirect("News.aspx?Save=this");
                }
                catch
                {
                    message.Text = "Cập nhật thất bại !";
                }
            }
            else
            {
                //Them moi tin tuc
                newsbo = NewsBO.NewNewsBO();
                newsbo.Title = txttitle.Text;
                newsbo.CategoryID = Convert.ToInt32(dltendanhmuc.SelectedValue);
                newsbo.NewsContent = txtnewscontent.Text;
                newsbo.CreatedDate = DateTime.Now;
                newsbo.ViewCount = 0;
                newsbo.IsActive = isactive.Checked;
                newsbo.ViewCount = 0;
                if (FileUpload_Image.FileName.Length > 0)
                {
                    postImage(FileUpload_Image);
                    if (retun == false) return;
                }
                try
                {
                    newsbo.Save();
                    message.Text = "Thêm thành công";
                    Response.Redirect("News.aspx?Save=Success");
                }
                catch
                {
                    message.Text = "Thêm thất bại";
                }
            }
        }

        protected void lbthuy_Click(object sender, EventArgs e)
        {
            FileUpload_Image.Visible = false;
            txtimage.Visible = true;
            lbtthaydoi.Visible = true;
            lbthuy.Visible = false;
        }

        protected void lbtthaydoi_Click(object sender, EventArgs e)
        {
            txtimage.Visible = false;
            lbtthaydoi.Visible = false;
            FileUpload_Image.Visible = true;
            lbthuy.Visible = true;
        }

        private void postImage(FileUpload filename)
        {
            try
            {
                if (filename.HasFile)
                {
                    if (filename.FileBytes.Length < 512000)
                    {
                        _fileImageName = filename.FileName.Replace(" ", "_");

                        string formatFile = Path.GetExtension(_fileImageName);
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG"))
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("~/TotalUpload/ImagesTotal/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                filename.SaveAs(Server.MapPath("~/TotalUpload/ImagesTotal/" + _fileImageName));
                                //deleteExitsImage(txtlink.Text);
                                //txtlink.Text = _fileImageName;
                                try
                                {
                                    newsbo.UrlImage = _fileImageName;
                                }
                                catch
                                {
                                    newsbo.UrlImage = "";
                                }
                            }
                            catch (Exception)
                            {
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.')", true);
                                retun = false;
                                return;
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng ảnh (.jpg , .gif, .png)')", true);
                            retun = false;
                            return;
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kích thước ảnh không quá 500Kb.')", true);
                        retun = false;
                        return;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chưa chọn hỉnh ảnh đại diện. !')", true);
                    retun = false;
                    return;
                }
            }
            catch { }
        }

        private static string ImageFileName(string fileName)
        {
            Random r = new Random();
            return r.Next(0, 10000).ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + fileName;
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("~/TotalUpload/ImagesTotal/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }
    }
}